package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"vehicle-order-mgr/cache"
	"vehicle-order-mgr/model"
)

func CarAdd(c *gin.Context) {
	car_name := c.PostForm("car_name")
	car_price := c.PostForm("car_price")
	car_num := c.PostForm("car_num")
	car_type := c.PostForm("car_type")
	data := model.Car{
		CarName:  car_name,
		CarPrice: car_price,
		CarNum:   car_num,
		CarType:  car_type,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
}
func OrderAdd(c *gin.Context) {
	order_price := c.PostForm("order_price")
	order_time := c.PostForm("order_time")
	order_status := c.PostForm("order_status")
	data := model.Order{
		OrderPrice:  order_price,
		OrderTime:   order_time,
		OrderStatus: order_status,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
}

func CarOrderList(c *gin.Context) {

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var orders []model.CarOrder
	redis_key := "car_order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"cars.car_name as CarName",
			"cars.car_price as CarPrice",
			"cars.car_num as CarNum",
			"cars.car_type as CarType",
			"orders.order_price as OrderPrice",
			"orders.order_time as OrderTime",
			"orders.order_status as OrderStatus",
		).Joins("LEFT JOIN cars ON cars.id=orders.cid").
			Offset(offset).Limit(size).Debug().Find(&orders)
		jsonData, _ := json.Marshal(orders)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orders)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  orders,
		"total": total,
	})
}
func CarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var orders model.CarOrder
	redis_key := "car_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"cars.car_name as CarName",
			"cars.car_price as CarPrice",
			"cars.car_num as CarNum",
			"cars.car_type as CarType",
			"orders.order_price as OrderPrice",
			"orders.order_time as OrderTime",
			"orders.order_status as OrderStatus",
		).Joins("LEFT JOIN cars ON cars.id=orders.cid").
			Where("orders.id=?", id).
			Debug().Find(&orders)
		jsonData, _ := json.Marshal(orders)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orders)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": orders,
	})
}
